package com.titaniue.java1;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @program: JavaSenior
 * @description:
 * @author: renfei.huang
 * @create: 2021-10-26 22:56
 */
public class URLTest1 {


    public static void main(String[] args) {

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            URL url = new URL("http://localhost:8080/examples/zzz.jpg");


            urlConnection = (HttpURLConnection)url.openConnection();


            urlConnection.connect();

            inputStream = urlConnection.getInputStream();

            fileOutputStream = new FileOutputStream("day10\\zzzz2.jpg");

            byte [] buffer = new byte[1024];

            int len;

            while ((len = inputStream.read(buffer))!=-1){
                fileOutputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源

            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            if(urlConnection!=null){
                urlConnection.disconnect();
            }


        }

    }
}
